<template>
  <el-form
    :model="examForm"
    :rules="examRule"
    ref="examForm"
    @keyup.enter.native="onSubmit"
    label-width="80px"
    v-loading="loading"
  >
    <el-row :gutter="20" style="margin: 0">
      <el-col :span="6" :offset="18" class="learn-drawer-range-box-buttons">
        <el-button
          class="el-icon-check"
          type="text"
          @click="onSubmit"
          style="color: #67C23A;font-size:24px"
        />
        <el-button
          class="el-icon-close"
          type="text"
          @click="onClose"
          style="color: #F56C6C;font-size: 24px"
        />
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin: 0">
      <el-col :span="12">
        <el-form-item label="考试名称" prop="name">
          <el-input v-model="examForm.name" placeholder="考试名称" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="试卷名称" prop="paperName">
<!--          v-if="parseInt(testType) !== 2"-->
<!--          v-if="examForm.status"-->
          <el-input :value="examRow.paperName" placeholder="试卷名称" disabled readonly>
            <el-button
              type="text"
              class="el-icon-edit"
              slot="suffix"
              @click="selectExamFn"
            >选择试卷</el-button>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
<!--        v-if="parseInt(testType) !== 2"-->
        <el-form-item label="组织机构" prop="institutional" v-if="this.module === 1">
          <el-input
            v-model="examForm.institutional"
            placeholder="组织机构"
            clearable
          />
<!--          :disabled="examForm.status"-->
        </el-form-item>
      </el-col>
      <el-col :span="12">
<!--        v-if="parseInt(testType) !== 2"-->
        <el-form-item label="考试地点" prop="place"  v-if="this.module === 1">
          <el-input
            type="text"
            v-model="examForm.place"
            placeholder="考试地点"
            clearable
          />
        </el-form-item>
<!--        :disabled="examForm.status"-->
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin: 0">
      <el-col :span="12"  v-if="this.module === 1">
        <el-form-item label="考试分类" prop="cateId">
          <el-input
            placeholder="请选择分类"
            :value="current.name"
            type="text"
            readonly
          >
<!--            :disabled="examForm.status"-->
            <template slot="suffix">
              <el-button
                class="el-icon-edit"
                @click="checkSort"
                type="text"
              >选择分类</el-button>
<!--              :disabled="examForm.status"-->
            </template>
          </el-input>
        </el-form-item>
      </el-col>
<!--      <el-col :span="12">-->
<!--        <el-form-item label="考试描述" prop="brief">-->
<!--          <el-input-->
<!--            :disabled="examForm.status"-->
<!--            v-model="examForm.brief"-->
<!--            placeholder="考试简介说明"-->
<!--            clearable-->
<!--          />-->
<!--        </el-form-item>-->
<!--      </el-col>-->
    </el-row>

    <el-row :gutter="20" style="margin: 0">
      <el-col :span="24" v-if="this.module === 1">
        <el-form-item label="考试时间" prop="timeRange">
          <el-date-picker
            v-model="examForm.timeRange"
            type="datetimerange"
            v-if="!examForm.status"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
<!--          value-format="timestamp"-->
          <template v-else>
            <el-date-picker
              v-model="examForm.timeRange[0]"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="开始时间"
            />至
            <el-date-picker
              v-model="examForm.timeRange[1]"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              placeholder="结束时间"
            />
<!--            disabled-->
          </template>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin: 0">
      <el-col :span="14">
        <el-form-item label="考试时长" prop="duration">
          <el-radio-group   v-model="time_type" @change="timeTypeChange">
<!--            <el-radio-button label="-1">无限</el-radio-button>-->
<!--            <el-radio-button label="1">时长</el-radio-button>-->
          </el-radio-group>
          <el-tooltip class="item" effect="dark" content="注：按分钟计算" placement="top-start">
            <el-input-number
              v-model="examForm.duration"
              controls-position="right"
              :min="1"
              :precision="0"
              clearable
            />
<!--          :disabled="examForm.status"-->
          </el-tooltip>
        </el-form-item>
        <el-form-item label="及格分数" prop="passMark">
          <el-input-number
            v-model="examForm.passMark"
            controls-position="right"
            :min="1"
            :precision="0"
            clearable
          />
          <!--          :disabled="examForm.status"-->
        </el-form-item>
      </el-col>
      <el-col :span="10">
        <el-form-item label="考试类型" v-if="this.module === 1">
          <el-radio-group
            v-model="examForm.examTypeStatus"
          >
            <el-radio-button :label="1">模拟考试</el-radio-button>
            <el-radio-button :label="2">正式考试</el-radio-button>
          </el-radio-group>
        </el-form-item>



      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin: 0">
      <el-col :span="10">
        <el-form-item label="发布范围" prop="number" v-if="this.module === 1">
          <el-radio-group
            v-model="examForm.publisherScope"
          >
            <el-radio-button :label="0">全部</el-radio-button>
            <el-radio-button :label="1">APP</el-radio-button>
            <el-radio-button :label="2">PC</el-radio-button>
          </el-radio-group>
        </el-form-item>
<!--        v-show="parseInt(testType) !== 2"-->
<!--        number-->
        <el-form-item label="考试次数" prop="number_type">
          <el-radio-group
            v-model="number_type"
            @change="numberTypeChange"
          >
            <el-radio-button :label="0">无限</el-radio-button>
            <el-radio-button :label="1">一次</el-radio-button>
            <el-radio-button :label="2">多次</el-radio-button>
          </el-radio-group>
          <el-input-number
            v-if="parseInt(number_type) > 1"
            v-model="examForm.number"
            :min="2"
            :max="99999"
            controls-position="right"
            :precision="0"
          />
          <p
            v-if="parseInt(number_type) > 1"
            style="font-size: 12px; color: #999"
          >(大于2次时，只能进行一次考试，其余次数为补考次数;最大次数为99999)</p>
        </el-form-item>
        <el-form-item label="归档" v-if="this.module === 1">
          <el-tooltip content="是否归入一人一档" placement="top">
            <el-switch
              v-model="examForm.putFile"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="切屏交卷" v-if="this.module === 1">
          <el-switch
            v-model="examForm.switchScreenForceSubmit"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch><br />
          <span v-if="examForm.switchScreenForceSubmit === 1">切换页面超过 <el-input-number  v-model="examForm.blurCount" :controls="false" :precision="0"  :min="0" />次后，将被强制交卷，切其他页面<el-input-number  v-model="examForm.switchScreenSecond" :controls="false" :precision="0"  :min="0" />秒后即判定为切屏。</span>
        </el-form-item>
      </el-col>
    </el-row>
<!--    <hr />-->
    <exam-type
      v-if="this.module === 1"
      ref="examType"
      v-show="parseInt(testType) !== 2"
      :setUserList="setUserList"
      :form="examForm"
      :examTypeChange="examTypeChange"
      :examUserArrClose="examUserArrClose"
      :setLoading="setLoading"
      :handleSelectionChange="handleSelectionChange"
    />

    <el-dialog
      title="分类管理"
      :visible.sync="dialogFormVisible"
      :show-close="false"
      append-to-body
      width="40%"
    >
      <paper-cate
        ref="paperCate"
        v-if="paperCate"
        :setCurrent="setCurrent"
        :current="current"
        :url="{
          update:'/exam-admin/exam/cate/update',
          save:'/exam-admin/exam/cate/save',
          delete:'/exam-admin/exam/cate/delete',
          tree:'/exam-admin/exam/cate/tree'
        }"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </el-form>
</template>

<script>
import paperCate from './../paper/papercate'
import SearchForm from '../../../components/search-form/search-form'
import ExamType from '../../../components/examType/exam-type'

export default {
  name: 'exam-info-form',
  components: { ExamType, SearchForm, paperCate },
  data() {
    let validatePass = (rule, value, callback) => {
      if (
        !this.examRow.paperName ||
        this.examRow.paperName === '' ||
        this.examRow.paperName == null
      ) {
        return callback(new Error('试卷不存在，请重新选择'))
      }
      callback()
    }
    return {
      module: 1,
      pickerOptions: {},
      testTypeArr: ['正式考试', '模拟考试', '三违考试'],
      loading: false,
      paperCate: false,
      dialogFormVisible: false,
      current: { id: '', name: '' },
      examForm: {
        id: '',
        name: '',
        institutional: '',
        cateId: '',
        putFile: 0,
        switchScreenForceSubmit: 1,
        switchScreenSecond: 20,
        blurCount: 5,
        examType: 0,
        examTypeStatus: 1,
        status: false,
        place: '',
        publisherScope: 0,
        brief: '',
        duration: -1,
        passMark: '',
        number: -1,
        timeRange: ['', ''],
        type: 1
      },
      // examRow: {
      //   type: Object,
      //   default: {
      //     paperName: '',
      //     id: null,
      //     paperInfo: null,
      //     courseId: ''
      //   }
      // },
      courseId: '',
      time_type: 1,
      number_type: 0,
      setUserList: [],
      selectUserList: {},
      examRule: {
        name: [
          { required: true, message: '考试名称不能为空', trigger: 'blur' }
        ],
        paperName: [{ validator: validatePass, trigger: 'blur' }],
        cateId: [
          { required: true, message: '考试分类id不能为空', trigger: 'blur' }
        ],
        timeRange: [
          { required: true, message: '考试时间不能为空', trigger: 'change' }
        ],
        // duration: [
        //   { required: true, message: '考试时长不能为空', trigger: 'blur' }
        // ],
        passMark: [
          { required: true, message: '及格分数不能为空', trigger: 'blur' }
        ],
        // institutional: [
        //   {required: true, message: '组织机构不能为空', trigger: 'blur'}
        // ],
        number: [
          { required: true, message: '考试次数不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  props: {
    handleClose: Function,
    examInfoFormSubmit: Function,
    selectExamFn: Function,
    testType: Number,
    setExamRow: {
      type: Function,
      default: _ => ({})
    },
    examRow: {
      type: Object,
      default: {
        paperName: '',
        id: null,
        paperInfo: null,
        courseId: ''
      }
    },
    setTestType: {
      type: Function,
      default: _ => ({})
    },
    setaddOperation: {
      type: Function,
      default: _ => ({})
    }
  },
  methods: {
    timeTypeChange(val) {
      this.examForm.duration =
        parseInt(val) === -1
          ? -1
          : this.examForm.duration
      this.$nextTick(_ => this.$refs['examForm'].validateField('duration'))
    },
    numberTypeChange(val) {
      this.examForm.number =
        parseInt(val) === 0
          ? -1
          : parseInt(val) === 1
          ? 1
          : this.examForm.number
      this.$nextTick(_ => this.$refs['examForm'].validateField('number'))
    },
    initSearchForm(obj) {
      this.$refs.examType.$refs.searchForm.init(obj)
    },
    getExamInfo(id, module, courseId) {
      this.courseId = courseId
      this.module = module
      this.number_type = 0
      this.examForm = {
        id: '',
        name: '',
        institutional: '',
        cateId: '',
        status: false,
        place: '',
        brief: '',
        putFile: 0,
        examType: 0,
        switchScreenForceSubmit: 1,
        switchScreenSecond: 20,
        blurCount: 5,
        examTypeStatus: 1,
        duration: -1,
        passMark: '',
        publisherScope: 0,
        number: -1,
        timeRange: '',
        type: 1
      }
      this.examForm.type = this.testType || 1
      this.setUserList = []
      this.current = {}
      if (module === 1) {
        this.$refs.examType.pagination.page = 1
        this.$refs.examType.pagination.limit = 10
      }
      if (id) {
        this.$http({
          url: this.$http.adornUrl(`/exam-admin/exam/info/${id}`),
          method: 'post'
        }).then(res => {
          if (res && res.code === 200) {
            this.examForm = {
              id: res.data.id,
              name: res.data.name,
              institutional: res.data.institutional,
              status: !!res.data.status,
              place: res.data.place,
              putFile: res.data.putFile,
              switchScreenForceSubmit: res.data.switchScreenForceSubmit,
              switchScreenSecond: res.data.switchScreenSecond,
              blurCount: res.data.blurCount,
              brief: res.data.brief,
              duration: Number(res.data.duration),
              publisherScope: res.data.publisherScope,
              passMark: res.data.passMark,
              paperId: res.data.paperId,
              number: res.data.number,
              timeRange: [res.data.startTime, res.data.endTime],
              type: Number(res.data.type),
              examType: Number(res.data.publisherType),
              examTypeStatus: Number(res.data.examType)
            }
            this.time_type = res.data.duration >= 0 ? 1 : -1
            this.number_type = res.data.number > 0 ? res.data.number : 0
            this.setTestType(Number(res.data.type))
            if (res.data.userInfoEntities && res.data.userInfoEntities.length) {
              if (res.data.status) {
                res.data.userInfoEntities.forEach(x => {
                  x.isEdit = true
                })
              }
              this.setUserList = res.data.userInfoEntities
            } else {
              this.setUserList = []
            }
            this.pickerOptions.disabledDate = time =>
              time.getTime() < parseInt(res.data.etime)
            if (Number(res.data.publisherType) && this.setUserList.length) {
              this.initSearchForm({
                userIds: this.setUserList.map(x => x.userId).join(',')
              })
            }
            this.setCurrent({ id: res.data.cateId, name: res.data.cateName })
            if (res.data.paperId && res.data.paperName) {
              this.setExamRow({
                paperName: res.data.paperName,
                id: res.data.paperId
              })
            }
          }
        })
      }
    },
    searchFormInit() {
      this.$refs.examType.$refs.searchForm.search({
        userIds: this.setUserList.map(x => x.userId).join(',')
      })
    },
    examUserArrClose(item, index) {
      this.setUserList.splice(index, 1)
      this.searchFormInit()
    },
    onClose() {
      this.examForm = {
        name: '',
        institutional: '',
        cateId: '',
        status: false,
        place: '',
        putFile: 0,
        brief: '',
        duration: '',
        passMark: '',
        publisherScope: 0,
        number: '',
        timeRange: '',
        type: 1,
        examType: 0,
        examTypeStatus: 1
      }
      this.setUserList = []
      this.current = {}
      // this.setExamRow({paperName: '', id: ''})
      if (this.module === 1) {
        this.$refs.examType.pagination.page = 1
        this.$refs.examType.pagination.limit = 10
      }
      this.handleClose()
    },
    onSubmit() {
      if (this.module === 1) {
        this.$refs['examForm'].validate(valid => {
          if (valid) {
            this.loading = true
            this.$http({
              url: this.$http.adornUrl(
                `/exam-admin/exam/${!this.examForm.id ? 'save' : 'update'}`
              ),
              method: 'post',
              data: {
                module: this.module,
                id: this.examForm.id,
                switchScreenForceSubmit: this.examForm.switchScreenForceSubmit,
                switchScreenSecond: this.examForm.switchScreenSecond,
                blurCount: this.examForm.blurCount,
                name: this.examForm.name,
                putFile: this.examForm.putFile,
                cateId: this.examForm.cateId,
                examType: this.examForm.examTypeStatus,
                duration: this.examForm.duration,
                publisherScope: this.examForm.publisherScope,
                passMark: this.examForm.passMark,
                startTime: this.examForm.timeRange.length
                  ? this.examForm.timeRange[0]
                  : '',
                endTime: this.examForm.timeRange.length
                  ? this.examForm.timeRange[1]
                  : '',
                paperId: this.examRow.id,
                paperInfo: this.examRow.paperInfo,
                brief: this.examForm.brief,
                userIds: this.examForm.examType
                  ? this.setUserList.map(x => x.userId).join(',')
                  : '',
                number: this.examForm.number,
                publisherType:
                  parseInt(this.testType) === 2 ? 0 : this.examForm.examType,
                type: this.testType,
                place: this.examForm.place,
                institutional: this.examForm.institutional
              }
            })
              .then(data => {
                if (data && data.code === 200) {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500
                  })
                  this.loading = false
                  this.visible = false
                  this.examInfoFormSubmit()
                  this.setaddOperation(data.data)
                } else {
                  this.$message.error(data.msg)
                }
                this.loading = false
              })
              .catch(() => {
                this.loading = false
              })
          }
        })
      } else {
        this.$refs['examForm'].validate(valid => {
          if (valid) {
            this.loading = true
            this.$http({
              url: this.$http.adornUrl(
                 `/train-admin/course/addCourseExam`
              ),
              method: 'post',
              data: {
                // eslint-disable-next-line no-undef
                courseId: this.courseId,
                module: this.module,
                examId: this.examForm.id || undefined,
                name: this.examForm.name,
                cateId: this.examForm.cateId,
                duration: this.examForm.duration,
                publisherScope: this.examForm.publisherScope,
                passMark: this.examForm.passMark,
                paperId: this.examRow.id,
                paperInfo: this.examRow.paperInfo,
                brief: this.examForm.brief,
                number: this.examForm.number,
                type: this.testType
              }
            })
              .then(data => {
                if (data && data.code === 200) {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500
                  })
                  this.loading = false
                  this.visible = false
                  this.examInfoFormSubmit()
                  this.$emit('refreshDataList')
                } else {
                  this.$message.error(data.msg)
                }
                this.loading = false
              })
              .catch(() => {
                this.loading = false
              })
          }
        })
      }
    },
    setLoading(val) {
      this.loading = val
    },
    passMark() {
      // eslint-disable-next-line no-useless-escape
      this.examForm.passMark = this.examForm.passMark.replace('.', '')
    },
    duration() {
      // eslint-disable-next-line no-useless-escape
      this.examForm.duration = this.examForm.duration.replace('.', '')
    },
    handleSelectionChange(val) {
      if (val.length) {
        this.setUserList = this.setUserList.concat(val)
        this.searchFormInit()
      }
    },
    setCurrent(data) {
      if (data.id) {
        this.current = data
        this.examForm.cateId = data.id
        this.$nextTick(_ => this.$refs['examForm'].validateField('cateId'))
      }
    },
    checkSort() {
      this.dialogFormVisible = true
      this.paperCate = true
      this.$nextTick(() => {
        this.$refs.paperCate.init()
      })
    },
    examTypeChange(val) {
      this.examForm.examType = val
      if (val) {
        this.initSearchForm({
          userIds: this.setUserList.map(x => x.userId).join(',')
        })
      }
    }
  }
}
</script>
